package com.lambkit.module.cms.web.controller;

import com.jfinal.kit.PathKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.lambkit.common.util.DateTimeUtils;
import com.lambkit.common.util.RequestUtils;
import com.lambkit.db.sql.column.Example;
import com.lambkit.module.cms.Cms;
import com.lambkit.module.cms.common.CmsConsts;
import com.lambkit.module.cms.common.CmsConsts.RefType;
import com.lambkit.module.cms.common.CmsResult;
import com.lambkit.module.cms.common.CmsResultConstant;
import com.lambkit.module.cms.common.Paginator;
import com.lambkit.module.cms.core.template.TemplateManager;
import com.lambkit.module.cms.rpc.model.*;
import com.lambkit.module.upms.UpmsManager;
import com.lambkit.module.upms.rpc.model.UpmsUser;
import com.lambkit.web.controller.LambkitController;
import org.apache.commons.lang.StringUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * kms首页控制器
 * Created by shuzheng on 2017/3/26.
 */
//@RequestMapping(value = "/km")
public class KmController extends LambkitController {

    //private static final Log LOG = Log.getLog(KmsController.class);
    private static String CODE = "km";

    /**
     * 知识库首页
     * @param page
     * @param sort
     * @param order
     * @param request
     * @param model
     * @return
     */
    //@RequestMapping(value = "", method = RequestMethod.GET)
    public void index() {
    	int page = getParaToInt(0, 1);
		String sort = getPara(1, "orders");
		String order = getPara(2, "desc");
        // 系统id
    	Example cmsSystemExample = CmsSystem.sql().andCodeEqualTo(CODE).example();
        CmsSystem system = CmsSystem.service().findFirst(cmsSystemExample);
        setAttr("system", system);
        // 该系统类目
        Example cmsCategoryExample = CmsCategory.sql().andSystemIdEqualTo(system.getSystemId()).example();
        cmsCategoryExample.setOrderBy("orders asc");
        List<CmsCategory> categories = CmsCategory.service().find(cmsCategoryExample);
        setAttr("categories", categories);
        // 该系统标签
        Example cmsTagExample = CmsTag.sql().andSystemIdEqualTo(system.getSystemId()).example();
        cmsTagExample.setOrderBy("orders asc");
        List<CmsTag> tags = CmsTag.service().find(cmsTagExample);
        setAttr("tags", tags);
        // 该系统文章列表
        int rows = 10;
        Example cmsArticleExample = CmsArticle.sql().andStatusEqualTo(1)
                .andSystemIdEqualTo(system.getSystemId()).example();
        if (!StringUtils.isBlank(sort) && !StringUtils.isBlank(order)) {
            cmsArticleExample.setOrderBy(sort + " " + order);
        }
        Page<CmsArticle> articles = CmsArticle.service().paginate(page, rows, cmsArticleExample);
        setAttr("articles", articles);
        setAttr("paginator", new Paginator(articles, getRequest()));
        render(TemplateManager.me().getCurrentWebPath() + "/" + CODE + "/index.html");
    }
    
    /**
     * 我的知识库首页
     */
    public void user() {
    	// 系统id
    	Example cmsSystemExample = CmsSystem.sql().andCodeEqualTo(CODE).example();
        CmsSystem system = CmsSystem.service().findFirst(cmsSystemExample);
        setAttr("system", system);
    	render(TemplateManager.me().getCurrentWebPath() + "/" + CODE + "/user.html");
    }
    
    /**
     * 公共知识库首页
     */
    public void pub() {
    	// 系统id
    	Example cmsSystemExample = CmsSystem.sql().andCodeEqualTo(CODE).example();
        CmsSystem system = CmsSystem.service().findFirst(cmsSystemExample);
        setAttr("system", system);
    	render(TemplateManager.me().getCurrentWebPath() + "/" + CODE + "/public.html");
    }

    /**
     * 新增回复
     * @param articleId
     * @param cmsComment
     * @param request
     * @return
     */
    //@RequestMapping(value = "/comment/{articleId}", method = RequestMethod.POST)
    //@ResponseBody
    public void comment() {
    	Long articleId = getParaToLong("articleId");
    	CmsComment cmsComment = getModel(CmsComment.class, "comment");
    	// 系统id
    	Example cmsSystemExample = CmsSystem.sql().andCodeEqualTo(CODE).example();
		CmsSystem system = CmsSystem.service().findFirst(cmsSystemExample);
        long time = System.currentTimeMillis();
        cmsComment.setCtime(DateTimeUtils.parse(time));
        cmsComment.setRefid(articleId);
        cmsComment.setReftype(CmsConsts.RefType.Article.value());
        UpmsUser user = getAttr("upmsUser") ==null ? UpmsManager.me().currentUser() : getAttr("upmsUser");
        if(user!=null) cmsComment.setUserId(user.getUserId());
        cmsComment.setStatus(1);
        cmsComment.setIp(RequestUtils.getIpAddress(getRequest()));
        cmsComment.setAgent(getHeader("User-Agent"));
        cmsComment.setSystemId(system.getSystemId());
        boolean flag = cmsComment.save();
        renderJson(new CmsResult(CmsResultConstant.SUCCESS, flag));
    }
    
    /**
     * 上传文件
     */
    public void upload() {
    	keepPara();
    	render(TemplateManager.me().getCurrentWebPath() + "/" + CODE + "/upload.html");
    }
    
    /**
     * 完成上传文件页面
     */
    public void uploadFinish() {
		List<String> uploadfiles = (List<String>) getSession().getAttribute(CmsConsts.SESSION_UPLOADS);
		if (uploadfiles != null) {
			List<CmsFile> list = new ArrayList<>();
			for (String u : uploadfiles) {
				try {
					CmsFile e = CmsFile.service().getByUuid(u);
					list.add(e);
				} catch (Exception e) {
				}
			}
			setAttr("files", list);
		}
		getSession().removeAttribute(CmsConsts.SESSION_UPLOADS);
		render(TemplateManager.me().getCurrentWebPath() + "/" + CODE + "/file/uploadfiles.html");
	}
    
    /**
     * 获取文件缩略图
     */
    public void thumbnail() {
    	String uuid = getPara(0);
    	String type = getPara(1, "png");
    	StringBuilder sb = new StringBuilder(Cms.config().getFilePath());
    	if(StrKit.notBlank(uuid)) {
    		CmsFile file = CmsFile.service().getByUuid(uuid);
    		if(file!=null) {
            	sb.append(file.getFilePath()).append(".").append(type);
    		}
    	}
    	System.out.println("[thumbnail] " + sb.toString());
    	File f = new File(sb.toString());
    	if(f.exists() && !f.isDirectory()) {
    		renderImage(sb.toString());
    	} else {
    		renderImage(PathKit.getWebRootPath() + "/static/center/img/books.png");
    	}
    }
    
    /**
     * 下载文件
     */
    public void download() {
    	UpmsUser user = getAttr("upmsUser") ==null ? UpmsManager.me().currentUser() : getAttr("upmsUser");
    	if(user==null) {
    		renderText("未登录，无法访问该链接！");
    		return;
    	}
    	String uuid = getPara(0);
    	String type = getPara(1);
    	StringBuilder sb = new StringBuilder(Cms.config().getFilePath());
    	if(StrKit.notBlank(uuid)) {
    		CmsFile file = CmsFile.service().getByUuid(uuid);
    		if(file!=null) {
    			if(StrKit.isBlank(type)) type = file.getFileExt();
            	sb.append(file.getFilePath()).append(".").append(type);
            	CmsAccess.service().addFileDownloadAccess(file.getFileId(), user.getUserId());
    		}
    	}
    	System.out.println("[download] " + sb.toString());
    	File f = new File(sb.toString());
    	if(f.exists() && !f.isDirectory()) {
    		renderImage(sb.toString());
    	} else {
    		renderText("文件不存在！");
    	}
    }
    
    /**
     * 文件浏览
     */
    public void file() {
    	String action = getPara(0);
    	if("new".equalsIgnoreCase(action)) {
    		render(TemplateManager.me().getCurrentWebPath() + "/" + CODE + "/file/newfile.html");
    	} else if("edit".equalsIgnoreCase(action)) {
    		String uuid = getPara(1);
    		CmsFile file = CmsFile.service().getByUuid(uuid);
        	setAttr("fileinfo", file);
        	render(TemplateManager.me().getCurrentWebPath() + "/" + CODE + "/file/edit.html");
    	} else if("list".equalsIgnoreCase(action)) {
    		UpmsUser user = getAttr("upmsUser") ==null ? UpmsManager.me().currentUser() : getAttr("upmsUser");
    		List<CmsFile> files = CmsFile.service().find(CmsFile.sql().andFileUserIdEqualTo(user.getUserId()).example());
        	setAttr("files", files);
        	render(TemplateManager.me().getCurrentWebPath() + "/" + CODE + "/file/list.html");
    	} else if("upload".equalsIgnoreCase(action)) {
    		setAttr("categoryId", getParaToLong(1, 1L));
        	render(TemplateManager.me().getCurrentWebPath() + "/" + CODE + "/file/upload.html");
    	} else {
    		String uuid = action;
    		CmsFile file = CmsFile.service().getByUuid(uuid);
    		file.joinUser();
        	setAttr("fileinfo", file);
        	UpmsUser user = getAttr("upmsUser") ==null ? UpmsManager.me().currentUser() : getAttr("upmsUser");
    		if(user!=null && !user.getUserId().equals(1L)) {
    			CmsAccess.service().addFileAccess(file.getFileId(), user.getUserId(), "read");
    		}
        	render(TemplateManager.me().getCurrentWebPath() + "/" + CODE + "/file/info.html");
    	}
    }
    
    /**
     * 网盘目录
     */
    public void disk() {
    	render(TemplateManager.me().getCurrentWebPath() + "/" + CODE + "/file/disk.html");
    }
    
    /**
     * 笔记目录
     */
    public void notes() {
    	render(TemplateManager.me().getCurrentWebPath() + "/" + CODE + "/note/index.html");
    }
    
    /**
     * 笔记浏览
     */
    public void note() {
    	String action = getPara(0);
    	if("new".equalsIgnoreCase(action)) {
    		//新增笔记
    		render(TemplateManager.me().getCurrentWebPath() + "/" + CODE + "/note/add.html");
    	} else if("edit".equalsIgnoreCase(action)) {
    		//编辑笔记
    		Long articleId = getParaToLong(1);
        	setAttr("note", CmsArticle.service().findById(articleId));
        	render(TemplateManager.me().getCurrentWebPath() + "/" + CODE + "/note/edit.html");
    	} else if("page".equalsIgnoreCase(action)) {
    		//笔记列表
    		int num = getParaToInt(1, 1);
    		int row = getParaToInt(2, 10);
    		UpmsUser user = getAttr("upmsUser") ==null ? UpmsManager.me().currentUser() : getAttr("upmsUser");
    		Page<CmsArticle> notes = CmsArticle.service().paginate(num, row, CmsArticle.sql().andUserIdEqualTo(user.getUserId()).example());
        	setAttr("notes", notes);
        	render(TemplateManager.me().getCurrentWebPath() + "/" + CODE + "/note/page.html");
    	} else if("category".equalsIgnoreCase(action)) {
    		//分类笔记列表
    		Long categoryId = getParaToLong(1);
    		int num = getParaToInt(2, 1);
    		int row = getParaToInt(3, 10);
    		Page<CmsArticle> notes = CmsArticle.service().paginateByCategoryIdInNormal(num, row, categoryId, "ctime desc");
        	setAttr("notes", notes);
        	render(TemplateManager.me().getCurrentWebPath() + "/" + CODE + "/note/category.html");
    	} else {
    		//浏览笔记
    		Long articleId = getParaToLong(0);
        	setAttr("note", CmsArticle.service().findById(articleId));
        	UpmsUser user = getAttr("upmsUser") ==null ? UpmsManager.me().currentUser() : getAttr("upmsUser");
    		if(user!=null && !user.getUserId().equals(1L)) {
    			CmsAccess.service().addArticleAccess(articleId, user.getUserId(), "read");
    		}
        	render(TemplateManager.me().getCurrentWebPath() + "/" + CODE + "/note/info.html");
    	}
    }
}